// 引入ASP.NET Core MVC控制器相关命名空间
using Microsoft.AspNetCore.Mvc;
// 引入项目中的数据传输对象
using Rabbit3.Api.Dto;
// 引入项目中的服务接口
using Rabbit3.Api.Services;
// 引入数据验证相关命名空间
using System.ComponentModel.DataAnnotations;

namespace Rabbit3.Api.Controllers
{
    /// <summary>
    /// 深加工管理控制器 - 负责处理深加工阶段相关的HTTP请求
    /// 提供深加工信息、供应商信息的增删改查功能
    /// </summary>
    [ApiController] // 标识这是一个API控制器，自动处理模型验证和错误响应
    [Route("api/[controller]")] // 设置路由前缀为 api/Processing
    public class ProcessingController : ControllerBase
    {
        // 深加工服务接口，用于处理深加工相关的业务逻辑
        private readonly IProcessingService _processingService;
        // 日志记录器，用于记录操作日志和错误信息
        private readonly ILogger<ProcessingController> _logger;

        /// <summary>
        /// 构造函数 - 通过依赖注入初始化控制器
        /// </summary>
        /// <param name="processingService">深加工服务实例</param>
        /// <param name="logger">日志记录器实例</param>
        public ProcessingController(IProcessingService processingService, ILogger<ProcessingController> logger)
        {
            // 初始化深加工服务
            _processingService = processingService;
            // 初始化日志记录器
            _logger = logger;
        }

        /// <summary>
        /// 根据溯源信息ID获取对应的深加工信息详情
        /// </summary>
        /// <param name="traceabilityId">溯源信息ID</param>
        /// <returns>深加工信息详情，如果不存在返回404</returns>
        [HttpGet("by-traceability/{traceabilityId}")] // HTTP GET请求，路径为 api/Processing/by-traceability/{traceabilityId}
        public async Task<ActionResult<ProcessingResponseDto>> GetByTraceabilityId(int traceabilityId)
        {
            try
            {
                // 根据溯源信息ID查询深加工信息
                var result = await _processingService.GetByTraceabilityIdAsync(traceabilityId);
                // 如果查询结果为空，返回404未找到
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的深加工信息", success = false });
                }
                // 返回200状态码和查询结果
                return Ok(result);
            }
            catch (Exception ex)
            {
                // 记录错误日志，包含溯源信息ID参数
                _logger.LogError(ex, "获取深加工信息失败，溯源信息ID: {TraceabilityId}", traceabilityId);
                // 返回500服务器内部错误
                return StatusCode(500, new { message = "获取失败", success = false });
            }
        }

        /// <summary>
        /// 根据ID获取深加工信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>深加工信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ProcessingResponseDto>> GetById(int id)
        {
            try
            {
                var result = await _processingService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的深加工信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取深加工信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "获取失败", success = false });
            }
        }

        /// <summary>
        /// 创建深加工信息
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<ActionResult<ProcessingResponseDto>> Create([FromBody] CreateProcessingDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.CreateAsync(createDto);
                return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建深加工信息失败");
                return StatusCode(500, new { message = "创建失败", success = false });
            }
        }

        /// <summary>
        /// 更新深加工信息
        /// </summary>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<ActionResult<ProcessingResponseDto>> Update([FromBody] UpdateProcessingDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.UpdateAsync(updateDto);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的深加工信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新深加工信息失败，ID: {Id}", updateDto.Id);
                return StatusCode(500, new { message = "更新失败", success = false });
            }
        }

        /// <summary>
        /// 删除深加工信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<object>> Delete(int id)
        {
            try
            {
                var result = await _processingService.DeleteAsync(id);
                if (!result)
                {
                    return NotFound(new { message = "未找到指定的深加工信息", success = false });
                }
                return Ok(new { message = "删除成功", success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除深加工信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "删除失败", success = false });
            }
        }

        /// <summary>
        /// 创建企业信息
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建结果</returns>
        [HttpPost("enterprise")]
        public async Task<ActionResult<EnterpriseResponseDto>> CreateEnterprise([FromBody] CreateEnterpriseDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.CreateEnterpriseAsync(createDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建企业信息失败");
                return StatusCode(500, new { message = "创建失败", success = false });
            }
        }

        /// <summary>
        /// 更新企业信息
        /// </summary>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut("enterprise")]
        public async Task<ActionResult<EnterpriseResponseDto>> UpdateEnterprise([FromBody] UpdateEnterpriseDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.UpdateEnterpriseAsync(updateDto);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的企业信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新企业信息失败，ID: {Id}", updateDto.Id);
                return StatusCode(500, new { message = "更新失败", success = false });
            }
        }

        /// <summary>
        /// 删除企业信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("enterprise/{id}")]
        public async Task<ActionResult<object>> DeleteEnterprise(int id)
        {
            try
            {
                var result = await _processingService.DeleteEnterpriseAsync(id);
                if (!result)
                {
                    return NotFound(new { message = "未找到指定的企业信息", success = false });
                }
                return Ok(new { message = "删除成功", success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除企业信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "删除失败", success = false });
            }
        }

        /// <summary>
        /// 创建供应商信息
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建结果</returns>
        [HttpPost("supplier")]
        public async Task<ActionResult<SupplierResponseDto>> CreateSupplier([FromBody] CreateSupplierDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.CreateSupplierAsync(createDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建供应商信息失败");
                return StatusCode(500, new { message = "创建失败", success = false });
            }
        }

        /// <summary>
        /// 更新供应商信息
        /// </summary>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut("supplier")]
        public async Task<ActionResult<SupplierResponseDto>> UpdateSupplier([FromBody] UpdateSupplierDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _processingService.UpdateSupplierAsync(updateDto);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的供应商信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新供应商信息失败，ID: {Id}", updateDto.Id);
                return StatusCode(500, new { message = "更新失败", success = false });
            }
        }

        /// <summary>
        /// 删除供应商信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("supplier/{id}")]
        public async Task<ActionResult<object>> DeleteSupplier(int id)
        {
            try
            {
                var result = await _processingService.DeleteSupplierAsync(id);
                if (!result)
                {
                    return NotFound(new { message = "未找到指定的供应商信息", success = false });
                }
                return Ok(new { message = "删除成功", success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除供应商信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "删除失败", success = false });
            }
        }
    }

    /// <summary>
    /// 屠宰管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class SlaughterController : ControllerBase
    {
        private readonly ISlaughterService _slaughterService;
        private readonly ILogger<SlaughterController> _logger;

        public SlaughterController(ISlaughterService slaughterService, ILogger<SlaughterController> logger)
        {
            _slaughterService = slaughterService;
            _logger = logger;
        }

        /// <summary>
        /// 根据溯源信息ID获取屠宰信息
        /// </summary>
        /// <param name="traceabilityId">溯源信息ID</param>
        /// <returns>屠宰信息</returns>
        [HttpGet("by-traceability/{traceabilityId}")]
        public async Task<ActionResult<SlaughterResponseDto>> GetByTraceabilityId(int traceabilityId)
        {
            try
            {
                var result = await _slaughterService.GetByTraceabilityIdAsync(traceabilityId);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的屠宰信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取屠宰信息失败，溯源信息ID: {TraceabilityId}", traceabilityId);
                return StatusCode(500, new { message = "获取失败", success = false });
            }
        }

        /// <summary>
        /// 根据ID获取屠宰信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>屠宰信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<SlaughterResponseDto>> GetById(int id)
        {
            try
            {
                var result = await _slaughterService.GetByIdAsync(id);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的屠宰信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取屠宰信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "获取失败", success = false });
            }
        }

        /// <summary>
        /// 创建屠宰信息
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<ActionResult<SlaughterResponseDto>> Create([FromBody] CreateSlaughterDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _slaughterService.CreateAsync(createDto);
                return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建屠宰信息失败");
                return StatusCode(500, new { message = "创建失败", success = false });
            }
        }

        /// <summary>
        /// 更新屠宰信息
        /// </summary>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<ActionResult<SlaughterResponseDto>> Update([FromBody] UpdateSlaughterDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _slaughterService.UpdateAsync(updateDto);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的屠宰信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新屠宰信息失败，ID: {Id}", updateDto.Id);
                return StatusCode(500, new { message = "更新失败", success = false });
            }
        }

        /// <summary>
        /// 删除屠宰信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<object>> Delete(int id)
        {
            try
            {
                var result = await _slaughterService.DeleteAsync(id);
                if (!result)
                {
                    return NotFound(new { message = "未找到指定的屠宰信息", success = false });
                }
                return Ok(new { message = "删除成功", success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除屠宰信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "删除失败", success = false });
            }
        }

        /// <summary>
        /// 创建企业信息
        /// </summary>
        /// <param name="createDto">创建DTO</param>
        /// <returns>创建结果</returns>
        [HttpPost("enterprise")]
        public async Task<ActionResult<EnterpriseResponseDto>> CreateEnterprise([FromBody] CreateEnterpriseDto createDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _slaughterService.CreateEnterpriseAsync(createDto);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建企业信息失败");
                return StatusCode(500, new { message = "创建失败", success = false });
            }
        }

        /// <summary>
        /// 更新企业信息
        /// </summary>
        /// <param name="updateDto">更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut("enterprise")]
        public async Task<ActionResult<EnterpriseResponseDto>> UpdateEnterprise([FromBody] UpdateEnterpriseDto updateDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _slaughterService.UpdateEnterpriseAsync(updateDto);
                if (result == null)
                {
                    return NotFound(new { message = "未找到指定的企业信息", success = false });
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新企业信息失败，ID: {Id}", updateDto.Id);
                return StatusCode(500, new { message = "更新失败", success = false });
            }
        }

        /// <summary>
        /// 删除企业信息
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("enterprise/{id}")]
        public async Task<ActionResult<object>> DeleteEnterprise(int id)
        {
            try
            {
                var result = await _slaughterService.DeleteEnterpriseAsync(id);
                if (!result)
                {
                    return NotFound(new { message = "未找到指定的企业信息", success = false });
                }
                return Ok(new { message = "删除成功", success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除企业信息失败，ID: {Id}", id);
                return StatusCode(500, new { message = "删除失败", success = false });
            }
        }
    }
}
